package com.aji.allcommon.interceptor;


//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.authority.SimpleGrantedAuthority;
//import org.springframework.security.core.context.SecurityContextHolder;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class UserInforInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.获取请求头中的用户信息
        if (request.getHeader("user-info") != null && request.getHeader("menus") != null) {
            Long userId = Long.valueOf(request.getHeader("user-info"));
            //将网关传递过来的权限转换格式
            String[] menus = request.getHeader("menus").replace("[", "").replace("]", "").split(",");
            List<String> userMenus = new ArrayList<>();
            for (String item:menus
                 ) {
                String trim = item.trim();
                userMenus.add(trim);
            }
            log.info("请求权限:{}",request.getHeader("menus") );
            List<SimpleGrantedAuthority> collect = userMenus.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
//         2.放入security上下文
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userId, null, collect);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
            log.info("当前用户：{}",usernamePasswordAuthenticationToken);
        }
//         3.放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 移除用户

    }
}
